<template>
<my-add-ip-detail></my-add-ip-detail>
<my-recorded-files></my-recorded-files>
<vs-modal :show.sync="showDownloadLink" effect="fade" width="800px">
  <div class="modal-header" slot="modal-header">
    <h4 class="modal-title">{{$t("recfiles.downloadLink")}}</h4>
  </div>
  <div class="modal-body" slot="modal-body">     
    <div class="my-dl-table">
      <my-table :cfg="dlCfg" :list="dlLists" :state="dlState.listsLoading"></my-table>
    </div>
  </div>
  <div class="modal-footer" slot="modal-footer">
    <button type="button" v-clipboard:copy="copyData">{{$t("recfiles.copyPath")}}</button>
    <button type="button" class="btn btn-default" @click.prevent="doExitDlLink">{{$t("common.quit")}}</button>
  </div> 
</vs-modal>
<form class="form-horizontal">
  <ul class="sidebar" >
    <li class="sidebar-main">
      <a class="rd-sidebar-toggle" >{{$t("recfiles.recordsFile")}}
        <button type="button" class="btn btn-default" @click.prevent="onScan"><span class="glyphicon glyphicon-search"></span></button>
        <button type="button" class="btn btn-default" @click.prevent="doDelete"><span class="glyphicon glyphicon-trash"></span></button>
      </a>
    </li>
    <li class="sidebar-title"><span>{{$t("recfiles.serverAddr") }}</span></li>
    <li class="sidebar-list" v-for="item in subList">
      <a href="javascript:;"  @click.prevent="onSelect(item)" :class="{active: selected===item.key}">
        <input type="checkbox" v-model="item.checkbox" :true-value=1 :false-value=0>
        {{item.key}}
        <button type="button" class="btn btn-xs btn-default" 
        :class="{'btn-default': item.state === 'connect',
                'btn-danger': item.state === 'disconnect', 
                'btn-success': item.state === 'connected'}"
         v-for="action in item.actions" @click="action.doClick(item)" @mouseover="moveon(item)" @mouseout="moveaway(item)">{{getStateText(item.state)}}</button>
      </a>
    </li>
  </ul>
  <my-navbar fixed="top" class="col-md-9 col-md-offset-3">
    <template slot="right">
      <label class="control-label">{{$t("recfiles.scanFilter")}}</label>
      <input type="text" class="form-control input-sm" v-model="inputedScene" debounce="500">
      <button class="btn btn-default" @click.prevent="doShowSearch"><span class="glyphicon glyphicon-search"></span>{{$t('common.search')}}</button>
    </template>
  </my-navbar>
  <div class="form-group col-md-12">.</div>
  <div class="form-group col-md-12">.</div>
  <div class="form-group" v-if="connect">
    <div class="col-md-9 col-md-offset-3">
      <my-table :cfg="cfg" :list="getLists | recordFilter" :state=""></my-table>
    </div>
  </div>
</form>
</template>

<script>
import _ from 'lodash'
import {http} from 'share/common/api.js'
import msgbox from 'libs/msgbox.js'
import async from 'async'
import ebus from 'libs/ebus.js'
import toast from 'libs/toast.js'
import locales from './locales.js'
import store from 'share/mediaserver/vuex/store.js'
import {getRecordFiles, getRecordFilesLink} from 'share/mediaserver/vuex/actions.js'
import {isValidStart, readableSize, readableTime} from 'libs/utils.js'

export default{
  locales,
  store,
  vuex: {
    getters: {
      lists: (state) => state.recordFiles,
      dlLists: (state) => state.recordFilesLink
    },
    actions: {
      getRecordFiles,
      getRecordFilesLink
    }
  },
  replace: true,
  filters: {
    recordFilter(getLists) {
      var filter = _.filter(getLists, (item) => {
        return item.scene.includes(this.inputedScene)
      })
      return filter
    }
  },
  data: function() {
    return{
      ipaddr: '',
      connect: false,
      scanDevCnt: 0,
      actionName: this.$t("common.connect"),
      selected: '',
      inputedScene: '',
      showDownloadLink: false,
      header: {
        icon: 'fa fa-list',
        title: '点播列表'
      },
      cfg: {
        checkable: false,
        showHead: true,
        columns: [{
          field: 'roomName',
          name: this.$t("recfiles.roomName"),
          width: 'auto'
        }, {
          field: 'scene',
          name: this.$t("recfiles.scene"),
          width: 'auto'
        }, {
          field: 'starttimeR',
          name: this.$t("recfiles.startTime"),
          width: 'auto'
        }, {
          field: 'durationR',
          name: this.$t("recfiles.shichang"),
          width: 'auto'
        }, {
          field: 'sizeR',
          name: this.$t("recfiles.daxiao"),
          width: 'auto'
        }, {
          field: 'playUrlLink',
          name: this.$t("recfiles.dianbo"),
          width: 'auto'
        }],
        operation: {
          name: this.$t("recfiles.caozuo"),
          width: 'auto',
          actions: [{
            icon: 'fa fa-download',
            doClick: this.doShowDownloadLink
          }]
        }
      },
      dlCfg: {
        checkable: false,
        showHead: true,
        columns: [{
          field: '_id',
          name: 'ID',
          width: 'auto'
        }, {
          field: 'downloadLink',
          name: this.$t("recfiles.lianjie"),
          width: 'auto'
        }]
      },
      dlState: {
        listsLoading: true
      },
      dlCopyContent: "",
      subList: [],
      roomsOptions: []
    }
  },
  computed: {
    getLists() {
      let sub = _.find(this.subList, {key: this.selected})
      if(sub) {
        return this.msgs
      } else {
        return this.lists
      } 
    },
    host() {
      return `http://${this.ipaddr}:6080`
    },
    copyData() {
      return this.dlCopyContent
    },
    msgs () {
      let sub = _.find(this.subList, {key: this.selected})
      if (sub) {
        return sub.msgs
      } else {
        return []
      }
    },
    state () {
      let sub = _.find(this.subList, {key: this.selected})
      if (sub) {
        return sub.state
      } else {
        return ''
      }
    }
  },
  methods: {
    getStateText(state) {
      if (state === 'connect') {
        return this.$t('common.connect')
      } else if (state === 'disconnect') {
        return this.$t('common.disconnect')
      } else if (state === 'connected') {
        return this.$t('recfiles.yilianjie')
      }
    },
    moveon(item) {
      if(item.state === 'connected') {
        item.state = 'disconnect'
      } else if(item.state === 'connect') {
        item.state = 'connect'
      }
    },
    moveaway(item) {
      if(item.state === 'disconnect') {
        item.state = 'connected'
      } else if(item.state === 'connect') {
        item.state = 'connect'
      } else if(item.state === 'connected') {
        item.state = 'connected'
      }
    },
    doExitDlLink() {
      this.showDownloadLink = false
    },
    doShowSearch() {
      if(this.msgs.length !== 0) {
        this.msgs.splice(0, this.msgs.length)
      }
      if(this.selected === '' || this.subList.length === 0) {
        this.showState(this.$t('recfiles.tianjia'), this.$t('recfiles.zuoce'), 'info')
      } else if(this.state === 'connect') {
        toast.w(this, this.$t('common.warning'), this.$t('error.notConnected'))
      } else {
        ebus.emit('show-recorded-files', this.selected)
      }
    },
    doConnect(item) {
      if(item.state === 'disconnect') {
        item.state = 'connect'
      } else if(item.state === 'connect') {
        item.state = 'connected'
      } 
      if(this.msgs.length !== 0) {
        this.msgs.splice(0, this.msgs.length)
      }
      this.ipaddr = item.key
      this.connect = false
      http(this.host, '/api/platform/cfg', 'GET', null, {timeout: 1000}).then(function(res) {
        if(res && res.data && res.data.code === 0) {
          /*setTimeout(function() {
            this.connect = true
          }.bind(this), 1000)*/
        }
      }.bind(this), function(err) {
        this.connect = false
        toast.w(this, this.$t('common.finish'), this.$t('error.notFound'))
      }.bind(this))
    },
    doSearchRecord(val) {
      this.getRecordFiles(this.selected, val)
      setTimeout(function() {
        if (this.lists.length === 0) {
          toast.w(this, this.$t('common.finish'), this.$t('error.notFound'))
        }
        this.msgs.splice(0, this.msgs.length)
        for(var i = 0; i < this.lists.length; i++ ) {
          this.msgs.splice(i, 0, this.lists[i])
        }
      }.bind(this), 1000)
    },
    doShowDownloadLink(id) {
      for (var i = 0; i < this.lists.length; i++) {
        if (this.lists[i]._id === id._id) {
          var record = this.lists[i]
        }
      }
      if (null == record) {
        toast.e(this, this.$t('common.fail'), this.$t('error.params'))
        return
      }
      this.dlLists.splice(0, this.dlLists.length)
      this.dlState.listsLoading = true
      this.dlCopyContent = record.folderLink
      var url = '/dev/record/items?listName=recordfiles&playUrl' + '=' + record.playUrl
      this.getRecordFilesLink(this.ipaddr, url)
      
      setTimeout(function() {
        this.showDownloadLink = true
        if (this.dlLists.length === 0) {
        toast.w(this, this.$t('common.finish'), this.$t('error.notFound'))
        }
      }.bind(this), 1000)
      this.dlState.listsLoading = false
    },
    onSelect (item) {
      this.selected = item.key
      item.checkbox = !item.checkbox
      this.connect = true
    },
    onScan () {
      ebus.emit('show-add-ip-detail')
    },
    scanDev (ipaddr, callback) {
      this.ipaddr = ipaddr
      http(this.host, '/api/platform/cfg', 'GET', null, {timeout: 1000})
      .then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.subList.push({
            key: ipaddr,
            index: 0,
            state: 'connect',
            msgs: [],
            checkbox: 0,
            actions: [{
              doClick: this.doConnect
            }]
          })
          /*if(window.localStorage) {
            var subList = []
            subList.splice(subList.length, 0, ipaddr)
            window.localStorage.setItem('subList', JSON.stringify(subList))
          }*/
          this.scanDevCnt++
        }
        callback()
      }.bind(this), function(res) {
        callback()
      })
    },
    doDelete() {
      this.connect = false
      for(var i = 0; i < this.subList.length; i++ ) {
        if(this.subList[i].checkbox === true) {
          this.subList.splice(i, 1)
          this.doDelete()
        }
      }
    },
    onAddIp (ipList) {
      if (ipList.length > 15) {
        msgbox.showWait(this.$t('alert.plzWait'), this.$t('common.processing'), -1)
      }
      this.scanDevCnt = 0
      async.eachLimit(ipList, 15, function(item, callback) {
        let dev = _.find(this.subList, {ipaddr: item})
        if (dev) {
          callback()
          return
        }
        this.scanDev(item, callback)
      }.bind(this), function(err) {
        if (ipList.length > 15) {
          msgbox.close()
        }
        if (this.scanDevCnt > 0) {
          toast.s(this, this.$t('common.finish'), this.$t('alert.findResult', {cnt: this.scanDevCnt}))
        } else {
          toast.w(this, this.$t('common.finish'), this.$t('error.notFound'))
        }
      }.bind(this))
    },
    loadSubList() {
      if(window.localStorage) {
        let str = window.localStorage.getItem('subList')
        if(!str) {
          return
        }
        let subList = JSON.parse(str)
        this.subList.splice(0, this.subList.length)
        /*for(var i = 0; i < subList.length; i++) {
          this.subList[i].key = subList[i]
        }*/
      }
    },
    showState(title, text, type){
      msgbox.alert({
        title: title,
        text: text,
        type: type,
        showCancelButton: false,
        confirmButtonColor: "#DD6B55",
        cancelButtonText: this.$t("common.cancel"),
        confirmButtonText: this.$t("common.confirm"),
        closeOnConfirm: false        
      },
      function() {
        setTimeout(function() {
          swal.close()
        }.bind(this), ) 
      }.bind(this))
    }
  },
  ready() {
    ebus.on('add-ip', this.onAddIp)
    ebus.on('show-url', this.doSearchRecord)
    //this.loadSubList()
  }
}
</script>

<style>
.my-dl-table {
  max-height: 400px;
  overflow-y: auto 
}
</style>